<template>
  <view class="container">
    <!-- Header -->
    <view class="header">
      <view class="result-icon">
        <uni-icons
            :color="scoreResult.isPerfect ? '#28a745' : scoreResult.accuracy >= 80 ? '#17a2b8' : '#ffc107'"
            :type="scoreResult.isPerfect ? 'checkmarkempty' : scoreResult.accuracy >= 80 ? 'checkmarkempty' : 'closeempty'"
            size="60"
        ></uni-icons>
      </view>
      <view class="result-text">
        {{ scoreResult.isPerfect ? '完美答题！' : scoreResult.accuracy >= 80 ? '恭喜完成！' : '继续加油！' }}
      </view>
      <view class="score-display">
        <text class="score-value">{{ scoreResult.score }}</text>
        <text class="score-label">分</text>
      </view>
    </view>

    <!-- Stats -->
    <view class="stats-section">
      <view class="stats-grid">
        <view class="stat-item">
          <text class="stat-value">{{ scoreResult.correctCount }}</text>
          <text class="stat-label">正确题数</text>
        </view>
        <view class="stat-item">
          <text class="stat-value">{{ scoreResult.totalQuestions }}</text>
          <text class="stat-label">总题数</text>
        </view>
        <view class="stat-item">
          <text class="stat-value">{{ scoreResult.accuracy }}%</text>
          <text class="stat-label">正确率</text>
        </view>
        <view class="stat-item">
          <text class="stat-value">{{ formatTime(scoreResult.totalTime) }}</text>
          <text class="stat-label">用时</text>
        </view>
        <view class="stat-item">
          <text class="stat-value">{{ scoreResult.averageTime }}s</text>
          <text class="stat-label">平均用时</text>
        </view>
        <view class="stat-item">
          <text class="stat-value">{{ scoreResult.baseScore }}</text>
          <text class="stat-label">基础分</text>
        </view>
      </view>
    </view>

    <!-- Time Bonus -->
    <view v-if="scoreResult.timeBonus > 0" class="bonus-section">
      <view class="bonus-title">
        <uni-icons color="#ffc107" size="20" type="star"></uni-icons>
        <text>时间奖励 +{{ scoreResult.timeBonus }}分</text>
      </view>
      <view class="bonus-desc">恭喜你在{{ formatTime(scoreResult.totalTime) }}内完成答题，获得时间奖励！</view>
    </view>

    <!-- Wrong Answers Review -->
    <view v-if="wrongQuestions.length > 0" class="review-section">
      <view class="section-title">
        <uni-icons color="#dc3545" size="20" type="closeempty"></uni-icons>
        <text>错误题目回顾</text>
      </view>
      <view class="review-list">
        <view
            v-for="(question, index) in wrongQuestions"
            :key="index"
            class="review-item"
        >
          <view class="review-question">
            <math-formula 
              :formula-name="question.formulaName"
              :latex-formula="question.latexFormula"
            ></math-formula>
          </view>
          <view class="review-answers">
            <view class="user-answer">
              <text class="label">你的答案：</text>
              <text class="value">{{ question.options[question.userAnswer] }}</text>
            </view>
            <view class="correct-answer">
              <text class="label">正确答案：</text>
              <text class="value">{{ question.correctAnswer }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- Action Buttons -->
    <view class="actions">
      <button class="action-btn secondary-btn" @tap="retry">
        <uni-icons color="#007AFF" size="20" type="refresh"></uni-icons>
        <text>再练一次</text>
      </button>
      <button class="action-btn primary-btn" @tap="goHome">
        <uni-icons color="#ffffff" size="20" type="home"></uni-icons>
        <text>返回首页</text>
      </button>
    </view>
  </view>
</template>

<script>
import Storage from '@/utils/storage.js';
import ScoreCalculator from '@/utils/score-calculator.js';
import CommonUtils from '@/utils/common.js';
import MathFormula from '@/components/common/math-formula.vue';

export default {
  components: {
    MathFormula
  },
  data() {
    return {
      questions: [],
      scoreResult: {
        totalQuestions: 0,
        correctCount: 0,
        wrongCount: 0,
        accuracy: 0,
        totalTime: 0,
        averageTime: 0,
        baseScore: 0,
        timeBonus: 0,
        score: 0,
        isPerfect: false
      }
    }
  },
  computed: {
    wrongQuestions() {
      return this.questions.filter(q => !q.isCorrect);
    }
  },
  onLoad() {
    this.loadResult();
    this.calculateStats();
    this.saveRecord();
  },
  methods: {
    // 加载答题结果
    loadResult() {
      const result = getApp().globalData.speedFormulaChoiceResult;
      if (result) {
        this.questions = result.questions;
        this.scoreResult.totalTime = (result.endTime - result.startTime) / 1000;
      }
    },

    // 计算统计数据
    calculateStats() {
      // 使用专门的公式选择题分数计算函数
      const scoreResult = ScoreCalculator.calculateSpeedFormulaChoiceScore(this.questions, this.scoreResult.totalTime);
      this.scoreResult = scoreResult;
    },

    // 保存记录
    saveRecord() {
      const record = {
        id: Date.now().toString(),
        type: 'speed-formula-choice',
        score: this.scoreResult.score,
        correctCount: this.scoreResult.correctCount,
        totalCount: this.scoreResult.totalQuestions,
        accuracy: this.scoreResult.accuracy,
        totalTime: this.scoreResult.totalTime,
        averageTime: this.scoreResult.averageTime,
        timestamp: new Date().toISOString()
      };

      const records = Storage.get('speed_formula_choice_records', []);
      records.unshift(record);
      
      // 只保留最近50条记录
      if (records.length > 50) {
        records.splice(50);
      }
      
      Storage.set('speed_formula_choice_records', records);
    },

    // 格式化时间
    formatTime(seconds) {
      return CommonUtils.formatTime(seconds);
    },

    // 再练一次
    retry() {
      uni.navigateBack({
        delta: 2
      });
    },

    // 返回首页
    goHome() {
      uni.switchTab({
        url: '/pages/index/index'
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx;
}

.header {
  background: linear-gradient(135deg, #8a2be2, #9370db);
  padding: 60rpx 40rpx;
  text-align: center;
  color: white;

  .result-icon {
    margin-bottom: 20rpx;
  }

  .result-text {
    font-size: 40rpx;
    font-weight: bold;
    margin-bottom: 30rpx;
  }

  .score-display {
    .score-value {
      font-size: 80rpx;
      font-weight: bold;
      margin-right: 10rpx;
    }

    .score-label {
      font-size: 30rpx;
    }
  }
}

.stats-section {
  padding: 40rpx;
  margin-bottom: 30rpx;

  .stats-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 20rpx;
    background: white;
    border-radius: 15rpx;
    padding: 30rpx;
    box-shadow: 0 5rpx 15rpx rgba(0, 0, 0, 0.05);

    .stat-item {
      text-align: center;

      .stat-value {
        display: block;
        font-size: 36rpx;
        font-weight: bold;
        color: #007AFF;
        margin-bottom: 10rpx;
      }

      .stat-label {
        font-size: 24rpx;
        color: #666;
      }
    }
  }
}

.bonus-section {
  background: white;
  margin: 0 40rpx 30rpx;
  border-radius: 15rpx;
  padding: 30rpx;
  box-shadow: 0 5rpx 15rpx rgba(0, 0, 0, 0.05);

  .bonus-title {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 30rpx;
    font-weight: bold;
    color: #ffc107;
    margin-bottom: 10rpx;

    text {
      margin-left: 10rpx;
    }
  }

  .bonus-desc {
    font-size: 26rpx;
    color: #666;
    text-align: center;
  }
}

.review-section {
  background: white;
  margin: 0 40rpx 30rpx;
  border-radius: 15rpx;
  padding: 30rpx;
  box-shadow: 0 5rpx 15rpx rgba(0, 0, 0, 0.05);

  .section-title {
    display: flex;
    align-items: center;
    font-size: 30rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 30rpx;

    text {
      margin-left: 10rpx;
    }
  }

  .review-list {
    .review-item {
      padding: 20rpx 0;
      border-bottom: 1rpx solid #eee;

      &:last-child {
        border-bottom: none;
      }

      .review-question {
        margin-bottom: 20rpx;
        font-size: 28rpx;
        line-height: 1.5;
      }

      .review-answers {
        display: flex;
        justify-content: space-between;

        .user-answer,
        .correct-answer {
          .label {
            font-size: 24rpx;
            color: #666;
          }

          .value {
            font-size: 28rpx;
            font-weight: bold;
            margin-left: 10rpx;
          }
        }

        .user-answer {
          .value {
            color: #dc3545;
          }
        }

        .correct-answer {
          .value {
            color: #28a745;
          }
        }
      }
    }
  }
}

.actions {
  display: flex;
  justify-content: center;
  gap: 30rpx;
  padding: 0 40rpx;

  .action-btn {
    flex: 1;
    height: 80rpx;
    border-radius: 40rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28rpx;
    font-weight: bold;
    border: none;

    text {
      margin-left: 10rpx;
    }

    &.secondary-btn {
      background: white;
      color: #007AFF;
      border: 2rpx solid #007AFF;
    }

    &.primary-btn {
      background: #007AFF;
      color: white;
    }
  }
}
</style>